<template>
  <div class="detailsEchart">
    <div id="myChart" ref="chart" class="echartsContainer"></div>
    <div class="baseDataline"></div>
  </div>
</template>

<script>
import 'echarts/lib/chart/bar'
import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/title'
import 'echarts/lib/component/grid'
import 'echarts/lib/component/dataZoom'

import * as echarts from 'echarts/lib/echarts'
// import 'zrender/lib/svg/svg' // svg模式
import { echartDataZoom } from '@/utils/common'
export default {
  props: ['xAxisData', 'seriesData', 'dataType', 'titleContent', 'echartsTitle', 'UnitLevel'],
  data() {
    return {
      drawObj: {}
    }
  },
  mounted() {
    this.drawLine(this.allData)
  },
  methods: {
    hideTip(ev, ec) {
      // (ev) => {
      if (ev.target.localName !== 'canvas') {
        ec.dispatchAction({
          type: 'hideTip'
        })
      }
    },
    splitstr(str) {
      if (str.length <= 10) return str + '<br/>'
      const num = Math.ceil(str.length / 8)
      let split = ''
      for (let i = 0; i < num; i++) {
        split += str.substr(i * 8, i * 8 + 8) + '<br/>'
      }
      return split
    },
    fillStr(str) {
      const n = (str + '').substr(0, 1) - 0 + 1
      return n + ''.padStart((str + '').length - 1, '0') - 0
    },
    // percent
    filtrationpercent(data) {
      const nameText = '百分比'
      const targetArr = data.seriesData.map(e => e === 0 ? '0.0' : (Math.round(e * 10000) / 100).toFixed(1))
      const maxNum = Math.ceil(Math.max(...targetArr))
      const fillstrMaxNum = this.fillStr(maxNum)
      data.seriesData = targetArr
      const leftn = (fillstrMaxNum + '').length * 10 + 15 + 'px'
      return {
        // text: '各' + data.titleContent + data.echartsTitle + `（${nameText}）`,
        hasPercent: true,
        nameText,
        xAxisData: data.xAxisData,
        maxNum,
        fillstrMaxNum,
        seriesData: data.seriesData,
        leftn
      }
    },
    // 金额
    filtrationnumber(data) {
      let nameText
      const targetArr = data.seriesData.map(e => e - 0) // .toFixed(1))
      const maxNum = Math.ceil(Math.max(...targetArr))
      let fillstrMaxNum = this.fillStr(maxNum)
      let leftn = (maxNum + '').length
      let fillStrLength = (fillstrMaxNum + '').length
      if (this.UnitLevel < 10000) {
        data.seriesData = targetArr.map(e => e === 0 ? '0.0' : e.toFixed(1))
        nameText = '元'
      } else if (this.UnitLevel >= 10000 && this.UnitLevel < 100000000) {
        data.seriesData = targetArr.map(e => e === 0 ? '0.0' : (e / this.UnitLevel).toFixed(1))
        fillstrMaxNum = this.fillStr(Math.ceil(Math.max(...data.seriesData)))
        fillStrLength = (fillstrMaxNum + '').length
        nameText = '万'
      } else if (this.UnitLevel >= 100000000) {
        data.seriesData = targetArr.map(e => e === 0 ? '0.0' : (e / this.UnitLevel).toFixed(1))
        fillstrMaxNum = this.fillStr(Math.ceil(Math.max(...data.seriesData)))
        fillStrLength = (fillstrMaxNum + '').length
        nameText = '亿'
      }
      leftn = fillStrLength === 1 ? '25px' : fillStrLength < 3 ? fillStrLength * 11 + 'px' : fillStrLength * 10 + 'px'
      return {
        // text: '各' + data.titleContent + data.echartsTitle + (nameText ? `（${nameText}）` : ''),
        hasPercent: false,
        nameText,
        xAxisData: data.xAxisData,
        maxNum,
        fillstrMaxNum,
        seriesData: data.seriesData,
        leftn
      }
    },
    // ren
    filtrationperson(data) {
      // let nameText
      const targetArr = data.seriesData.map(e => Math.floor(e - 0).toFixed(0))
      const maxNum = Math.ceil(Math.max(...targetArr))
      const fillstrMaxNum = this.fillStr(maxNum)
      data.seriesData = targetArr
      let leftn = (maxNum + '').length
      const fillStrLength = (fillstrMaxNum + '').length
      const nameText = '人'
      // if (leftn < 5) {
      //   nameText = ''
      // } else if (leftn >= 5 && leftn < 9) {
      //   data.seriesData = targetArr.map(e => (e / 10000).toFixed(1))
      //   fillstrMaxNum = this.fillStr(Math.ceil(Math.max(...data.seriesData)))
      //   fillStrLength = (fillstrMaxNum + '').length
      //   nameText = '万'
      // } else if (leftn >= 9) {
      //   data.seriesData = targetArr.map(e => (e / 100000000).toFixed(1))
      //   fillstrMaxNum = this.fillStr(Math.ceil(Math.max(...data.seriesData)))
      //   fillStrLength = (fillstrMaxNum + '').length
      //   nameText = '亿'
      // }
      leftn = fillStrLength === 1 ? '25px' : fillStrLength < 3 ? fillStrLength * 11 + 'px' : fillStrLength * 10 + 'px'
      return {
        // text: '各' + data.titleContent + data.echartsTitle + (nameText ? `（${nameText}）` : ''),
        hasPercent: false,
        nameText,
        xAxisData: data.xAxisData,
        maxNum,
        fillstrMaxNum,
        seriesData: data.seriesData,
        leftn
      }
    },
    drawLine(obj) {
      // return
      const _this = this
      if (obj.dataType === 'percent') {
        obj = this.filtrationpercent(obj)
      }
      if (obj.dataType === 'number') {
        obj = this.filtrationnumber(obj)
      }
      if (obj.dataType === 'person') {
        obj = this.filtrationperson(obj)
      }
      let nameMaxLength = 0
      obj.xAxisData.forEach(e => {
        if (e) {
          if (nameMaxLength < e.length) nameMaxLength = e.length
        }
      })
      // 基于准备好的dom，初始化echarts实例
      const chartDom = this.$refs.chart
      // const chartDom = document.getElementById('myChart')
      const myChart = echarts.init(chartDom)
      const option = {
        grid: {
          left: obj.leftn,
          right: 0,
          top: '15 %',
          bottom: nameMaxLength >= 4 || obj.xAxisData.length >= 6 ? '25%' : '10%',
          y2: 70
        },
        title: {
          // text: obj.text, // '各' + obj.titleContent + obj.echartsTitle + (nameText ? `（${nameText}）` : ''),
          textStyle: {
            fontSize: 14,
            fontWeight: 'normal',
            color: '#e9e9ed'
            // marginTop: 20
          }
        },
        tooltip: {
          trigger: 'axis',
          borderWidth: 0,
          // alwaysShowContent: false,
          // triggerOn: 'none',   放移动端测试
          axisPointer: {
            type: 'shadow'
          },
          textStyle: {
            color: '#e9e9ed'
          },
          extraCssText: 'z-index: 0',
          backgroundColor: '#393f52',
          formatter(params) {
            let html = _this.splitstr(params[0].name) // params[0].name + '<br/>'
            html += params[0].value === '-0.0' ? '-' : params[0].marker + params[0].value + (obj.hasPercent ? '%' : obj.nameText)
            return html + '<br>'
          }
        },
        xAxis: {
          data: obj.xAxisData,
          axisTick: {
            show: false
          },
          axisLine: {
            show: true
          },
          axisLabel: {
            interval: 0,
            rotate: nameMaxLength >= 4 || obj.xAxisData.length > 6 ? 55 : 0,
            color: '#e9e9ed',
            formatter(params) {
              if (params.length > 3) {
                return params.substr(0, 3) + '...'
              } else {
                return params
              }
            }
          },
          z: 10
        },
        yAxis: {
          type: 'value',
          splitNumber: obj.maxNum === 0 ? 1 : 4,
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#363A46'
            }
          },
          max: obj.fillstrMaxNum,
          min: 0,
          axisLabel: {
            formatter(params) {
              if (obj.hasPercent) {
                return params + '%'
              } else {
                return params
              }
            },
            textStyle: {
              show: true,
              color: '#e9e9ed',
              fontSize: '12'
            }
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          }
        },
        dataZoom:
          obj.seriesData.length > 10 ? echartDataZoom : [],
        series: [
          {
            type: 'bar',
            showBackground: false,
            barCategoryGap: '50%',
            barMaxWidth: 30,
            itemStyle: {
              normal: {
                color: function(params) {
                  if (params.dataIndex < 3) {
                    return '#FFB440'
                  }
                  return '#0A82FA'
                }
              }
            },
            data: obj.seriesData // hasPercent ? obj.seriesData.map(e => e.substr(0, e.length - 1)) : obj.seriesData
          }
        ]
      }
      // 绘制图表
      myChart.setOption(option, true)
      window.addEventListener('click', (ev) => {
        if (ev.target.localName !== 'canvas' && myChart) {
          myChart.dispatchAction({
            type: 'hideTip'
          })
        }
      })
    }
  },
  computed: {
    allData() {
      return {
        xAxisData: this.xAxisData.slice(0, 20),
        seriesData: this.seriesData.slice(0, 20),
        dataType: this.dataType, //  percent number person
        titleContent: this.titleContent,
        echartsTitle: this.echartsTitle
      }
    }
  },
  watch: {
    allData(val) {
      this.drawLine(val)
    }
  }
}
</script>

<style lang="scss" scoped>
.detailsEchart {
  .echartsContainer {
    height: 240px;
    // width: 290px;
    // margin: 10px auto;
    // background: $light-bc;
  }
  .baseDataline {
    height: 1px;
    margin: 16px -20px 12px -20px;
    width: 375px;
    background-color: $light-bc;
  }
}
</style>
